﻿using System;
using System.IO;
using UnityEditor;
using UnityEngine;

public class ExportObs
{
    static FileStream fs;
    static uint mapSize;

    [MenuItem("Tools/ExportObs", false, 10)]
    public static void Export()
    {
        if (OpenObsDataFile())
        {
            byte[] ObsData = GetObsDataFromCurrentScene();
            if (ObsData != null)
            {
                WriteObsData(ObsData);
            }
            else
            {
                Debug.Log("There is no cube added!");
            }
        }
        else
        {
            Debug.Log("Can't import ObsDataFile!");
        }
        fs.Close();
    }

    //打开文件
    static bool OpenObsDataFile()
    {
        //路径是在Assets下
        string obsFilePath = Application.dataPath + @"/Obs.data";
        try
        {
            fs = File.Open(obsFilePath, FileMode.Create);
        }
        catch (IOException e)
        {
            Debug.Log(e.Message);
            return false;
        }
        return true;
    }

    static byte[] GetObsDataFromCurrentScene()
    {
        byte[] temp = null; //获取游戏中的Cube
        GameObject[] gos = GameObject.FindGameObjectsWithTag("Block");
        if (0 != gos.Length)
        {
            var terrainData = Terrain.activeTerrain.terrainData;
            mapSize = Convert.ToUInt32(terrainData.size.x * terrainData.size.z);
            temp = new byte[mapSize];

            for (int i = 0; i < mapSize; i++)
            {
                temp[i] = 0;
            }
            foreach (GameObject go in gos)
            {
                //根据位置坐标算出数组中的索引
                var pos = go.transform.position;
                var x = Mathf.FloorToInt(pos.x);
                var z = (int)(Mathf.FloorToInt(pos.z) * terrainData.size.x);
                temp[x + z] = 1;
            }
        }
        return temp;
    }

    static void WriteObsData(byte[] obsData)
    {
        BinaryWriter bw = new BinaryWriter(fs);
        //首先写入地图大小,为简单起见，假定地图是正方形的，所以只需写入一边的长
        bw.Write(Convert.ToUInt16(Terrain.activeTerrain.terrainData.size.x));

        for (int i = 0; i < mapSize; i++)
        {
            bw.Write(obsData[i]);
        }

        bw.Flush(); bw.Close();
        Debug.Log("Export success!");
    }
}